package moe.server;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;

public class HttpLogInterceptor implements HttpProcessor {
	private static final Logger log = Logger.getLogger(HttpLogInterceptor.class.getName());

	private static final String RESPONSE_USE_TIME = "response_use_time";

	public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
		if (log.isLoggable(Level.INFO)) {
			context.setAttribute(RESPONSE_USE_TIME, System.currentTimeMillis());
			if (log.isLoggable(Level.FINE)) {
				log.fine("New request: " + request.getRequestLine());
			}
		}
	}

	public void process(HttpResponse response, HttpContext context) throws HttpException,
			IOException {
		if (log.isLoggable(Level.FINE)) {
			HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
			Object o = context.getAttribute(RESPONSE_USE_TIME);
			StringBuilder builder = new StringBuilder();
			builder.append(request.getRequestLine()).append(" - ").append(
					response.getStatusLine().getStatusCode()).append(" ").append(
					response.getStatusLine().getReasonPhrase());
			if (o != null) {
				long time = (Long) o;
				builder.append(", used time:").append(System.currentTimeMillis() - time)
						.append(
								"ms");
				log.fine(builder.toString());
			}
		}
	}

}
